package org.e_gold.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.e_gold.dao.LeagueDAO;
import org.e_gold.model.crawler.livescore.League;
import org.e_gold.util.DateUtil;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Thang Nguyen
 */
@Repository
public class LeagueDAOImpl extends AbstractGenericDAO<League> implements LeagueDAO {

	private static final Logger logger = Logger.getLogger(LeagueDAOImpl.class);

	public LeagueDAOImpl(){
		super(League.class);
	}

	@Override
	@Transactional
	public League getLeagueByName(String name) {
		try{
			Criteria crit = getCurrentSession().createCriteria(League.class);
			crit.add(Restrictions.like("name", name));
			Object result = crit.uniqueResult();
			if(result != null){
				League league = (League) result;

				return league;
			}
		}catch(Exception ex){
			ex.printStackTrace();
			logger.error(ex);
		}
		return null;
	}

	@Override
	@Transactional
	public void activeLeague(String strLeagueId) {
		try{
			//first, disable all League
			Query query = getCurrentSession().createSQLQuery(UPDATE_ALL_LEAGUE_TO_FALSE);
			query.executeUpdate();

			//finally update selected league to active status
			String SQLLeagueStatusToFalse = UPDATE_LEAGUE_STATUS_TO_TRUE.replace("idList", strLeagueId);
			Query q = getCurrentSession().createSQLQuery(SQLLeagueStatusToFalse);
			q.executeUpdate();
		}catch(Exception ex){
			ex.printStackTrace();
			logger.error(ex);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<League> getNearlyLeague(Number range) {
		Date[] dateRange = DateUtil.getDateInRange(range);
		Criteria crit = getCurrentSession().createCriteria(League.class);
		crit.add(Restrictions.between("modifyTimeStamp", dateRange[0], dateRange[1]));

		List<League> data = crit.list();
		List<League> retList = new ArrayList<League>();
		for(League ce : data){
			retList.add(ce);
		}
		return retList;
	}
}
